package org.zxp.encryption;

import io.jsonwebtoken.*;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;

/**
 * @program: effectiveJava
 * @description:
 * @author: X-Pacific zhang
 * @create: 2020-09-03 13:55
 **/
public class JWTTest {
    public static void main(String[] args) throws InterruptedException {
        String sharedTokenSecret = "hellooauthhellooauthhellooauthhellooauth";//密钥

        HashMap<String, Object> headerMap = new HashMap<>();
        HashMap<String, Object> payloadMap = new HashMap<>();
        headerMap.put("alg", "HS256");
        headerMap.put("typ", "JWT");
        payloadMap.put("sub", "zxp");
        payloadMap.put("name", "zxp");
        long exp = System.currentTimeMillis() + 1000*3;//3秒后过期
        //生成JWT令牌
        String jwts = Jwts.builder()
                .setHeaderParams(headerMap)
                .setClaims(payloadMap)
                .signWith(SignatureAlgorithm.HS256,sharedTokenSecret)
                .setExpiration(new Date(exp))//设置过期时间，如果超期，解析JWT令牌会报错
                .compact();
        System.out.println("jwt token:"+jwts);

        //Thread.sleep(3500);

        //解析JWT令牌
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(sharedTokenSecret+"salt").parseClaimsJws(jwts);
        JwsHeader header = claimsJws.getHeader();
        System.out.println(header);
        Claims body = claimsJws.getBody();
        System.out.println(body);



    }
}
